<template>
  <view class="w-full max-w-[750rpx] mx-auto min-h-screen bg-[#f6f8fa] p-[32rpx] box-border">
    <text class="block text-[48rpx] font-extrabold mb-[40rpx] text-center text-blue-600 drop-shadow">编辑体格检查</text>
    <FormView v-if="form.recordid" :fieldConfig="fieldConfig" :form="form" :showButtons="true" @submit="submitForm" />
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import Taro from '@tarojs/taro'
import { demographicBodyFields as fieldConfig } from './fields'
import FormView from '@/components/FormView.vue'
import { request } from '@/service/request'

const form = reactive<any>({})
const recordId = ref<string>('')

onMounted(async () => {
  // 获取路由参数
  const params = Taro.getCurrentInstance().router?.params
  if (params?.id) {
    recordId.value = params.id
    await loadRecordData(params.id)
  }
})

async function loadRecordData(id: string) {
  try {
    const result = await request.get<any>(`/health_records/demographic_body/demographicBodyInfo/queryById?id=${id}`, {}, {
      useErrMsg: true
    })

    console.log("result", result)
    
    if (result.success) {
      Object.assign(form, result.success)
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    Taro.showToast({ title: '加载数据失败', icon: 'error' })
  }
}

// 监听身高和体重变化，自动计算BMI
watch(() => [form.height, form.weight], ([height, weight]) => {
  if (height && weight) {
    const heightInMeters = parseFloat(height) / 100
    const bmi = (parseFloat(weight) / (heightInMeters * heightInMeters)).toFixed(1)
    form.bmi = bmi
  }
}, { immediate: true })

// 监听腰围和臀围变化，自动计算腰臀比
watch(() => [form.waistCircumference, form.hipCircumference], ([waist, hip]) => {
  if (waist && hip) {
    const ratio = (parseFloat(waist) / parseFloat(hip)).toFixed(2)
    form.waistHipRatio = ratio
  }
}, { immediate: true })

async function submitForm(form: any, fieldConfig: any) {
  try {
    // 表单验证
    

    // 提交数据
    const params = {
      ...form,
    }
    
    const result = await request.put<any>(`/health_records/demographic_body/demographicBodyInfo/update`, params, {
      useErrMsg: true
    })
    
    if (result) {
      Taro.showToast({ title: '更新成功', icon: 'success' })
      // 返回上一页
      setTimeout(() => {
        Taro.navigateBack()
      }, 1500)
    }
  } catch (error) {
    console.error('更新失败:', error)
    Taro.showToast({ title: '更新失败', icon: 'error' })
  }
}
</script>
